package com.github.shiqiyue.app.api.sapi.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.shiqiyue.app.api.sapi.common.SApiBaseController;
import com.github.shiqiyue.app.api.sapi.req.user.EditCurrentUserInfoReq;
import com.github.shiqiyue.app.api.sapi.req.user.UserAddReq;
import com.github.shiqiyue.app.api.sapi.req.user.UserEditReq;
import com.github.shiqiyue.app.api.sapi.req.user.UserPageReq;
import com.github.shiqiyue.app.api.sapi.result.user.UserDetailResult;
import com.github.shiqiyue.app.api.sapi.result.user.UserInfoResult;
import com.github.shiqiyue.app.api.sapi.result.user.UserPageResult;
import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.utils.EnumUtil;
import com.github.shiqiyue.app.config.security.sapi.SapiLoginUser;
import com.github.shiqiyue.app.modules.sys.entity.User;
import com.github.shiqiyue.app.modules.sys.enums.OperlogTypeEnum;
import com.github.shiqiyue.app.modules.sys.enums.UserStatusEnum;
import com.github.shiqiyue.app.modules.sys.service.IOperLogService;
import com.github.shiqiyue.app.modules.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.stream.Collectors;

/***
 * 系统用户信息
 * @author wenyao.wu
 * @date 2018/10/9
 */
@Api(tags = "系统用户")
@RestController
@RequestMapping("sapi/sys/user")
public class SApiUserController extends SApiBaseController {

    private static final Logger logger = LoggerFactory.getLogger(SApiUserController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IOperLogService operLogService;

    /***
     * 用户信息列表
     * @return
     */
    @PostMapping("page")
    public Result<UserPageResult> userPage(UserPageReq query) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(User.ADD_DATE);
        IPage<User> userPage = userService.page(query);
        UserPageResult userPageDTO = new UserPageResult();
        userPageDTO.setCurrent(userPage.getCurrent());
        userPageDTO.setSize(userPage.getSize());
        userPageDTO.setTotal(userPage.getTotal());
        userPageDTO.setRecords(userPage
                .getRecords()
                .stream()
                .map(item -> UserPageResult.Item.newInstance(item))
                .collect(Collectors.toList()));
        return Result.success(userPageDTO);
    }


    /***
     * 添加用户
     * @param userAddReq
     * @return
     */
    @PostMapping("add")
    public Result addUser(@Valid UserAddReq userAddReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (userService.countByName(userAddReq.getName()) > 0) {
            return Result.fail("用户名已存在");
        }
        User user = new User();
        user.setName(userAddReq.getName());
        user.setPassword(passwordEncoder.encode(userAddReq.getPassword()));
        user.setStatus(UserStatusEnum.ABLE);
        user.setAvatar("");
        user.setIntroduction("");
        userService.save(user);
        operLogService.addLog(getCurrentUser().getId(), OperlogTypeEnum.USER, "添加用户", null);
        return Result.success();
    }

    /****
     * 修改用户
     * @param userEditReq
     * @return
     */
    @PostMapping("edit")
    public Result editUser(@Valid UserEditReq userEditReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (userService.countByName(userEditReq.getName(), userEditReq.getId()) > 0) {
            return Result.fail("用户名已存在");
        }
        User updateParam = new User();
        if (StringUtils.isNotBlank(userEditReq.getPassword())) {
            updateParam.setPassword(passwordEncoder.encode(userEditReq.getPassword()));
        }
        updateParam.setAvatar(userEditReq.getAvatar());
        updateParam.setStatus(EnumUtil.getEnumByValue(UserStatusEnum.values(), userEditReq.getStatus()));
        updateParam.setId(userEditReq.getId());
        updateParam.setName(userEditReq.getName());
        userService.updateById(updateParam);
        operLogService.addLog(getCurrentUser().getId(), OperlogTypeEnum.USER, "修改用户", userEditReq.getId());

        return Result.success();
    }


    /***
     * 修改当前用户信息
     * @param editCurrentUserInfoReq
     * @return
     */
    @ApiOperation("修改当前用户信息")
    @PostMapping("current/edit")
    public Result editCurrentUserInfo(@Valid EditCurrentUserInfoReq editCurrentUserInfoReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return Result.fail("登录失效");
        }
        User updateParam = new User();
        if (StringUtils.isNotBlank(editCurrentUserInfoReq.getPassword())) {
            updateParam.setPassword(passwordEncoder.encode(editCurrentUserInfoReq.getPassword()));
        }
        updateParam.setAvatar(editCurrentUserInfoReq.getAvatar());
        updateParam.setId(getCurrentUser().getId());
        userService.updateById(updateParam);
        return Result.success();
    }

    /***
     * 用户详细信息
     * @param id
     * @return
     */
    @ApiOperation("用户详细信息")
    @PostMapping("detail")
    public Result<UserDetailResult> userDetail(Long id) {
        User user = userService.getById(id);
        UserDetailResult userDetailResult = UserDetailResult.newInstance(user);
        return Result.success(userDetailResult);
    }

    /***
     * 获取当前登录用户信息
     * @return
     */
    @ApiOperation("获取当前登录用户信息")
    @PostMapping("current/detail")
    public Result<UserInfoResult> getUserInfo(HttpSession httpSession) {
        String token = httpSession.getId();
        // 获取保存在session中用户信息
        SapiLoginUser sapiLoginUser = getCurrentLoginUser();
        User user = sapiLoginUser.getUser();
        UserInfoResult userInfoVO = new UserInfoResult();
        userInfoVO.setId(user.getId());
        userInfoVO.setToken(token);
        userInfoVO.setName(user.getName());
        userInfoVO.setAvatar(user.getAvatar());
        userInfoVO.setIntroduction(user.getIntroduction());
        userInfoVO.setRoles(sapiLoginUser.getPermissions());
        return Result.success(userInfoVO);
    }


}
